package net.yxsoft.kit;

public class SnowFlakeIdUtil {
    private static final long START_TIMESTAMP = 1609459200000L; // 设置起始时间戳为2021-01-01 00:00:00
    private static final long WORKER_ID_BITS = 5L;
    private static final long SEQUENCE_BITS = 12L;
    private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
    private static final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BITS);

    private long workerId;
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    public SnowFlakeIdUtil(long workerId) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException("Worker ID超出范围");
        }
        this.workerId = workerId;
    }

    public synchronized int generateUniqueInt() {
        long currentTimestamp = System.currentTimeMillis();
        if (currentTimestamp < lastTimestamp) {
            throw new RuntimeException("系统时钟回退，无法生成唯一整数");
        }

        if (currentTimestamp == lastTimestamp) {
            sequence = (sequence + 1) & MAX_SEQUENCE;
            if (sequence == 0) {
                currentTimestamp = waitNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = currentTimestamp;

        return (int) ((currentTimestamp - START_TIMESTAMP) << (WORKER_ID_BITS + SEQUENCE_BITS)
                | (workerId << SEQUENCE_BITS)
                | sequence) & Integer.MAX_VALUE;
    }

    private long waitNextMillis(long lastTimestamp) {
        long currentTimestamp = System.currentTimeMillis();
        while (currentTimestamp <= lastTimestamp) {
            currentTimestamp = System.currentTimeMillis();
        }
        return currentTimestamp;
    }

    public static void main(String[] args) {
        SnowFlakeIdUtil generator = new SnowFlakeIdUtil(1L); // 设置workerId为1
        for (int i = 0; i < 10; i++) {
            int uniqueInt = generator.generateUniqueInt();
            System.out.println(uniqueInt);
        }
    }

}


